package com.zx.cloud.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 * @Description:
 *
 * @author       Yan Weiwei
 * @Create Time: 2017年10月27日下午4:16:50
 */
public final class SmsCodeUtil {
	
	private static final Logger logger=Logger.getLogger(SmsCodeUtil.class);
	
	public static int getCodeRandom(){
		
		return (int)((Math.random()*9+1)*100000);
	}
	
	public static int sendSmsCode(Map<String, String> params){
		
		int returnInt = 0;
		
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		String url = null;
		if(params != null && !params.isEmpty()){
			for(Map.Entry<String, String> entity :params.entrySet()){
				//解析Map传递的参数，使用一个键值对对象BasicNameValuePair保存。
				if(!"SMS_URL".equals(entity.getKey())){
					list.add(new BasicNameValuePair(entity.getKey(), entity.getValue()));
				}else{
					url = entity.getValue();
				}
			}
		}
		
		try {
			//将请求的参数封装封装到HttpEntity中。
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "utf-8");
			
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(entity);
			
			CloseableHttpClient client = HttpClients.createDefault();
			
			logger.info("************************开始发送接口请求**********************************");
			
			CloseableHttpResponse res = client.execute(httpPost);
			
			if(res.getStatusLine().getStatusCode() == 200){
				//发送成功
				logger.info("************************短信发送成功**********************************");
			}else{
				HttpEntity resultEntity = res.getEntity();
				
				logger.info("************************错误码："+ res.getStatusLine().getStatusCode() + " " + res.getStatusLine().getReasonPhrase() +"**********************************");
				logger.info("************************错误原因是："+ EntityUtils.toString(resultEntity) +"**********************************");
			}
			
			returnInt = res.getStatusLine().getStatusCode();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return returnInt;
	}
}
